package com.sixmac.platform;

import com.google.common.base.Strings;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.annotation.Json;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.CourseChapter;
import com.sixmac.platform.intercept.UserIntercept;
import com.sixmac.service.CourseChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * CourseController
 * 2018-07-03 17:19:48
 *
 * @author Blade
 */
@Controller
@RequestMapping("/course")
public class CourseController extends BaseController {
    private static String CODE = "course";
    private static String PREFIX = "t_course";
    private static String LIST_SOURCE = "course.list";
    private static String BASE_PATH = "/platform/course/";

    @Autowired
    CourseChapterService service;

    @RequestMapping("/courseTreeList")
    @Json
    public AjaxResult courseTreeList() {
        String s = "select id,name, 0 as 'pId','false' as 'open' ,0 as sort,createtime from t_course \n" +
                " union\n" +
                " select id,name, courseId as 'pId','false' as 'open',sort,createtime from t_course_chapter where pid = 0\n" +
                " union\n" +
                " select id,name, pid as 'pId','false' as 'open',sort,createtime from t_course_chapter where pid != 0  order by sort ,createtime";
        List<Map> mapList = Db.selectList(s);
        return json(mapList);
    }


    @RequestMapping(KEY_MAIN)
    public String index(ModelMap mm) {
        mm.put("code", CODE);
        return BASE_PATH + "course.html";
    }

    @RequestMapping(KEY_ADD)
    public String add(ModelMap mm) {
        mm.put("code", CODE);
        return BASE_PATH + "course_add.html";
    }

    @RequestMapping(KEY_ADD + "/{id}")
    public String add(ModelMap mm, @PathVariable Integer id) {
        mm.put("code", CODE);
        CourseChapter courseChapter = service.findById(id);
        if (courseChapter != null) {
            mm.put("p", courseChapter.getPid());
            mm.put("courseId", courseChapter.getCourseId());
        }

        return BASE_PATH + "course_add.html";
    }

    @RequestMapping(KEY_EDIT + "/{id}")
    public String edit(@PathVariable Integer id, ModelMap mm) {
        CourseChapter course = service.findById(id);
        this.removeModel(course);
        mm.put("model", JsonKit.toJson(course));
        mm.put("id", id);
        mm.put("code", CODE);
        return BASE_PATH + "course_edit.html";
    }

    @RequestMapping(KEY_VIEW + "/{id}")
    public String view(@PathVariable Integer id, ModelMap mm) {
        CourseChapter course = service.findById(id);
        mm.put("model", JsonKit.toJson(course));
        mm.put("id", id);
        mm.put("code", CODE);
        return BASE_PATH + "course_view.html";
    }

    @ResponseBody
    @RequestMapping(KEY_LIST)
    public Object list() {
        Object grid = paginate(LIST_SOURCE, new UserIntercept());
        return grid;
    }

    @ResponseBody
    @RequestMapping(KEY_SAVE)
    public AjaxResult save() {
        CourseChapter course = mapping(PREFIX, CourseChapter.class);
        course.setPid(0);
        course.setCreatetime(new Date());
        course.setUpdatetime(new Date());
        this.convertModel(course);
        boolean temp = Blade.create(CourseChapter.class).saveAndSetKey(course);
        if (temp) {
            course.setCourseId(course.getId());
            service.update(course);
            return success(SAVE_SUCCESS_MSG);
        } else {
            return error(SAVE_FAIL_MSG);
        }
    }

    @ResponseBody
    @RequestMapping(KEY_UPDATE)
    public AjaxResult update() {
        CourseChapter course = mapping(PREFIX, CourseChapter.class);
        this.convertModel(course);
        boolean temp = service.update(course);
        if (temp) {
            return success(UPDATE_SUCCESS_MSG);
        } else {
            return error(UPDATE_FAIL_MSG);
        }
    }

    @ResponseBody
    @RequestMapping(KEY_REMOVE)
    public AjaxResult remove(@RequestParam String ids) {
        int cnt = service.deleteByIds(ids);
        if (cnt > 0) {
            return success(DEL_SUCCESS_MSG);
        } else {
            return error(DEL_FAIL_MSG);
        }
    }


    private void convertModel(CourseChapter courseChapter) {
        String categoryIds = courseChapter.getCategoryIds();
        if (!Strings.isNullOrEmpty(categoryIds)) {
            StringBuilder sb = new StringBuilder();
            String[] ids = Convert.toStrArray(categoryIds);
            for (String id : ids) {
                sb.append("<").append(id).append(">").append(",");
            }
            courseChapter.setCategoryIds(sb.toString());
        }

    }

    private void removeModel(CourseChapter courseChapter) {
        String categoryIds = courseChapter.getCategoryIds();
        if (!Strings.isNullOrEmpty(categoryIds)) {
            courseChapter.setCategoryIds(categoryIds.replaceAll("<", "").replaceAll(">", ""));
        }
    }

}
